﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace GiveAQuiz.Common.Mvvm
{
  public static class CommandHelper
  {
    /// <summary>
    /// Executes a Command without knowing the real type of the owner of the command.
    /// Allows loose coupling of View and ViewModel from code as well as bindings.
    /// </summary>
    /// <param name="commandOwner">The object which has a command on it (typically the ViewModel, or the DataContext of a View)</param>
    /// <param name="commandName">The name of the command to search for.</param>
    /// <param name="parameter">An optional parameter to to send to the command.</param>
    /// <returns>True if the command was found and is able to be executed, otherwise false.</returns>
    public static bool ExecuteCommand(object commandOwner, string commandName, object parameter = null)
    {
      var result = false;
      
      // Find the command if any
      Type ownerType = commandOwner.GetType();
      var commandProperty = ownerType.GetProperty(commandName);
      if (commandProperty != null)
      {
        var command = commandProperty.GetValue(commandOwner, new object[] { }) as ICommand;
        if (command != null)
        {
          // If we found a command, we can see if it can be executed.
          if (command.CanExecute(parameter))
          {
            // If so, execute it
            command.Execute(parameter);
            result = true;
          }
        }
      }

      return result;
    }

    public static bool ExecuteCommandOnProperty(object commandOwner, string propertyName, string commandName, object parameter = null)
    {
      var prop = commandOwner.GetType().GetProperty(propertyName);
      if (prop != null)
      {
        var value = prop.GetValue(commandOwner, new object[] { });
        return ExecuteCommand(value, commandName, parameter);
      }
      return false;
    }
  }
}
